package com.ironman.analyze.core.handler;

import com.ironman.analyze.core.compute.entity.HeadingWindowData;
import com.ironman.analyze.core.compute.entity.SpeedWindowData;
import com.ironman.analyze.core.compute.entity.VmgWindowData;
import com.ironman.analyze.core.compute.entity.WindEnvWindowData;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class VmgPostHandler {

    public void handler(WindEnvWindowData windEnvWindowData,
                        HeadingWindowData headingWindowData,
                        SpeedWindowData speedWindowData,
                        Consumer<VmgWindowData> vmgWindowDataConsumer) {
        Double angle = null;
        Double vmg = null;

        Double customAngle = null;
        Double customVmg = null;

        String windSourceBoatCode = null;
        Double windSpeed = null;
        Double windDirection = null;
        Double customWindSpeed = null;
        Integer customWindDirection = null;

        if (Objects.nonNull(windEnvWindowData) && Objects.nonNull(headingWindowData)) {
            windSourceBoatCode = windEnvWindowData.getTrainingBoatCode();
            windSpeed = windEnvWindowData.getWindSpeed();
            windDirection = windEnvWindowData.getWindDirection();
            customWindSpeed = windEnvWindowData.getCustomWindSpeed();
            customWindDirection = windEnvWindowData.getCustomWindDirection();

            Double headingM = headingWindowData.getHeadingM();
            if (Objects.nonNull(windDirection) && Objects.nonNull(headingM)) {
                double abs = Math.abs(headingM - windDirection);
                angle = abs <= 180 ? abs : 360 - abs;
                if (Objects.nonNull(speedWindowData)) {
                    Double speed = speedWindowData.getSpeed();
                    vmg = Math.cos(Math.toRadians(angle)) * speed;
                }
            }
            if (Objects.nonNull(customWindDirection) && Objects.nonNull(headingM)) {
                double abs = Math.abs(headingM - customWindDirection);
                customAngle = abs <= 180 ? abs : 360 - abs;
                if (Objects.nonNull(speedWindowData)) {
                    Double speed = speedWindowData.getSpeed();
                    customVmg = Math.cos(Math.toRadians(customAngle)) * speed;
                }
            }
        }

        VmgWindowData vmgWindowData = VmgWindowData.builder()
                .angle(angle)
                .vmg(vmg)
                .customAngle(customAngle)
                .customVmg(customVmg)
                .windSourceBoatCode(windSourceBoatCode)
                .windSpeed(windSpeed)
                .windDirection(windDirection)
                .customWindSpeed(customWindSpeed)
                .customWindDirection(customWindDirection)
                .build();

        vmgWindowDataConsumer.accept(vmgWindowData);
    }
}
